package com.wpen.unit.service.impl;

import java.net.InetAddress;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.wpen.unit.AppVariables;
import com.wpen.unit.service.RegistryService;
import com.wpen.unit.utils.EnvironmentUtil;
import com.wpen.unit.web.WebVariables;
import com.wpen.unit.web.dto.AgentRegistryRequest;
import com.wpen.unit.web.dto.AgentRegistryResponse;
import com.wpen.unit.web.utils.HttpService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class RegistryServiceImpl implements RegistryService {
	@Value("${wpen.os.network.name:}")
	private String networkName;
	@Value("${wpen.application.admin.service-path}")
	private String servicePath;
	@Value("${wpen.application.code.az}")
	private String azCode;
	@Value("${wpen.application.code.biz}")
	private String bizCode;
	@Value("${server.port}")
	private Integer port;

	@Override
	public AgentRegistryResponse registryMe() {
		// 获取自己的IP
		List<InetAddress> ipAddresses = EnvironmentUtil.getIpAddress(networkName);
		if (ipAddresses == null || ipAddresses.isEmpty() || ipAddresses.size() > 1) {
			log.error("ip address Exception. [" + ipAddresses + "] ");
			log.info("you can set values for parameter[wpen.os.network.name]");
			// 应用强制停止，不能启动。
			System.exit(1);
		}
		AppVariables.inetAddress = ipAddresses.get(0);
		AppVariables.jdkVersion = EnvironmentUtil.getJdkVersion();
		String[] jdkVers = AppVariables.jdkVersion.split("\\.");
		AppVariables.jdkLargeVersion = Integer.parseInt(jdkVers[0]);
		// 注册服务
		AgentRegistryRequest registryRequest = new AgentRegistryRequest();
		registryRequest.setAgentHostname(AppVariables.inetAddress.getHostName());
		registryRequest.setAgentIpv4(AppVariables.inetAddress.getHostAddress());
		registryRequest.setBizCode(networkName);
		registryRequest.setAgentPort(port);
		// 发送http请求注册
		HttpService<AgentRegistryResponse> httpService = new HttpService<>();
		AgentRegistryResponse agentRegistryResponse = httpService.proxyPostHttp(servicePath, WebVariables.URI_REGISTRY,
				null, registryRequest, AgentRegistryResponse.class);
		if (WebVariables.RESPONSE_SUCC_CODE.equals(agentRegistryResponse.getCode())) {
			log.info("Agent registration succeeded.");
		}
		return agentRegistryResponse;
	}

}
